import os
import requests
from flask import Flask, request, send_from_directory, render_template, jsonify
from flask_cors import CORS


app = Flask(__name__)
CORS(app,supports_credentials=True)

app.config['UPLOAD_FOLDER'] = './uploads'
app.config['ONLYOFFICE_URL'] = 'http://localhost'
app.config['ONLYOFFICE_API_KEY'] = 'OGLjO8Mq5Dj9ohRKjtR65vbp19JPxrbC2RYkUiBFJGM='
if not os.path.exists(app.config['UPLOAD_FOLDER']):
    os.makedirs(app.config['UPLOAD_FOLDER'])


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if 'file' not in request.files:
            return 'No file part'
        file = request.files['file']
        if file.filename == '':
            return 'No selected file'
        if file:
            filename = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
            file.save(filename)
            # Generate the document editor URL
            # doc_url = generate_doc_editor_url(filename)
            # return render_template('index.html', doc_url=doc_url)
    return render_template('index.html')


def generate_doc_editor_url(doc_path):
    url = f"{app.config['ONLYOFFICE_URL']}/web-apps/apps/api/documents/api.js"
    doc_info = {
        "document": {
            "url": f"http://{request.host}/{os.path.basename(doc_path)}",
            "fileType": "docx",
            "key": os.path.basename(doc_path),
            "title": os.path.basename(doc_path)
        },
        "documentType": "text",
        "editorConfig": {
            "callbackUrl": f"http://{request.host}/callback",
            "lang": "zh",
            "customization": {
                "leftMenu": False,
                "chat": False
            }
        }
    }
    response = requests.post(
        f"{app.config['ONLYOFFICE_URL']}/web-apps/apps/api/documents/api.js",
        json=doc_info,
        headers={"Authorization": f"Bearer {app.config['ONLYOFFICE_API_KEY']}"}
    )
    if response.status_code == 200:
        return response.json()['url']
    else:
        raise Exception("Failed to generate document editor URL")


@app.route('/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)


@app.route('/callback', methods=['POST'])
def callback():
    data = request.json
    # Process the callback data here
    print(data)
    return jsonify({"status": "success"})




if __name__ == '__main__':
    app.run()
